/**
 * SaveHelper
 */

 var SaveHelper = (function (){
    var uuids = [], callback = function (){}, isJumping = false;
    var timer, interval = 1000, limit = 60, count = 0;

    var getIndexByUuid = function (uuid){
        return uuids.indexOf(uuid);
    };

    var add = function (uuid){
        var index = getIndexByUuid(uuid);
        if (index === -1){
            uuids.push(uuid);
        }
    };

    var remove = function (uuid){
        var index = getIndexByUuid(uuid);
        if (index !== -1){
            uuids.splice(index, 1);
        }
        watchRequest();
    };

    var setJumping = function (jumping){
        isJumping = jumping;
    };

    var setCallback = function (fn){
        callback = fn;
    };

    var watching = function (){
        if (isJumping && count++ >= limit){
            isJumping = false;
            endTimer();
            callback();
        }
    };

    var startTimer = function (){
        timer = setInterval(watching, interval);
    };

    var endTimer = function (){
        clearInterval(timer);
        timer = null;
    };

    var watchRequest = function (){
        if (isJumping){
            if (!uuids.length){
                isJumping = false;
                endTimer();
                callback();
            } else {
                startTimer();
            }
        }
    };

    return {
        add: add,
        remove: remove,
        setJumping: setJumping,
        setCallback: setCallback,
        watchRequest: watchRequest
    }
 })();

 module.exports = SaveHelper;
